package cn.itzzx.lagou.mybatis.config;

import cn.itzzx.lagou.mybatis.io.Resources;
import cn.itzzx.lagou.mybatis.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * 解析xml配置文件
 * @author Martin
 * @date 2020-04-25
 * @see 1.0
 */
public class XmlConfigBuilder {

    private Configuration configuration;

    public XmlConfigBuilder(){
        configuration = new Configuration();
    }


    /**
     * 解析  mybatis 配置文件
     * @param inputStream
     * @return
     * @throws DocumentException
     * @throws PropertyVetoException
     */
    public Configuration parseXmlConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
        Document document = new SAXReader().read(inputStream);
        
        //获取根节点 <configuration></configuration>
        Element rootElement = document.getRootElement();

        //获取数据配置信息
        List<Element> propertyNodes = rootElement.selectNodes("//property");
        //用于存放数据库连接信息
        Properties properties = new Properties();
        for (Element propertyNode : propertyNodes) {
            String name = propertyNode.attributeValue("name");
            String value = propertyNode.attributeValue("value");
            properties.put(name,value);
        }
        //设置数据源
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));

        //将数据源放置configuration
        configuration.setDataSource(comboPooledDataSource);

        //解析mapper.xml映射文件
        List<Element> mapperNodes = rootElement.selectNodes("//mapper");
        for (Element mapperNode : mapperNodes) {
            XmlMappedBuilder xmlMappedBuilder = new XmlMappedBuilder(configuration);
            String mapperPath = mapperNode.attributeValue("resource");
            InputStream in = Resources.getResourceAsStream(mapperPath);
            xmlMappedBuilder.parseMapper(in);
        }

        //解析 <package /> 标签
        List<Element> packageNodes = rootElement.selectNodes("//package");
        for (Element packageNode : packageNodes) {
            //判断是否是package标签
            if("package".equals(packageNode.getName())){
                String mapperPackage = packageNode.attributeValue("name");
                configuration.addMappers(mapperPackage);
            }
        }


        return configuration;
    }


}
